package com.dz.lm.common.context;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.dz.lm.common.util.DzCache;
import com.dz.lm.common.utils.DateUtil;

/**
 * 平台上下文环境
 * @author zhanghairong
 * @since 2019-05-28
 */
@Component
public class GlobalContext {
	private static final Logger logger = LoggerFactory.getLogger(GlobalContext.class);
	
	private static ExecutorService executorService;
	
	public GlobalContext()
	{
		executorService = Executors.newFixedThreadPool(60);//初始化线程池
		logger.info("60个线程初始化完成");
		SetCache();
	}
	
	/**
	 * 服务启动时设置缓存（今日最大订单ID、100个订单编号list）
	 */
	public static void SetCache(){
		long todayMaxorderId = DzCache.getCacheCode("todayMaxorderId") == null ? 0l : Long.parseLong(DzCache.getCacheCode("todayMaxorderId").toString());
		long maxId = todayMaxorderId + 100;
		DzCache.setCacheCode("todayMaxorderId", maxId);
		List<String> orderIdList = new ArrayList<String>();
		String strTime = DateUtil.getTimeStrFormat(new Date());
		String suffix = "00000000";
		for (long i = todayMaxorderId + 1; i < maxId + 1; i++) {
			suffix = suffix + "" + i;
			suffix = suffix.substring(suffix.length()- 8, suffix.length());
			orderIdList.add(strTime + "" + suffix);
		}
		DzCache.setCacheCode("orderId", orderIdList);
	}
	
	public static ExecutorService getExecutorService() {
		return executorService;
	}
	
	/**
	 * 获得前台html结尾的路径
	 * @return
	 */
	public static String getRequestURI()
	{
		HttpServletRequest request = (HttpServletRequest)ThreadContext.get(ThreadContext.REQUEST);

		if (request==null)
		{
			return "";
		}
		
		String paras = request.getQueryString();
		if ( paras==null )
		{
			return(request.getRequestURI());
		}
		else
		{
			return(request.getRequestURI() + "?" + paras);
		}
	}
}
